import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { fetchPost } from '@/http'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        meta: { name: "首页", check: true },
        children: [
            {
                path: '/back_user',
                name: 'back_user',
                component: () => import("@/views/main/BackUserManage.vue"),
                meta: { name: "后台用户管理", check: true },
            },
            {
                path: '/front_user',
                name: 'front_user',
                component: () => import("@/views/main/FrontUserManage.vue"),
                meta: { name: "前台用户管理", check: true },
            },
            {
                path: '/bugs_manage',
                name: 'bugs_manage',
                component: () => import("@/views/main/BugsWorkManage.vue"),
                meta: { name: "爬虫管理", check: true },
            },
            {
                path: '/infos',
                name: 'infos',
                component: () => import("@/views/main/InfoManage.vue"),
                meta: { name: "信息列表", check: true },
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
        meta: { check: false },
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// HOOK
router.beforeEach((to, from, next) => {
    // 如果要check, 到服务器验证, 更新user信息, 如果没有跳转到登录页面
    if (to.meta && to.meta.check) {
        fetchPost("/backUser/getByToken")
            .then((res) => {
                store.commit("setUser", res.data);
                setBared(to);
                next();
            })
            .catch(() => {
                store.commit("resetHomeBread");
                router.push("/login");
            })
    } else {
        setBared(to);
        next();
    }
});

function setBared(to) {
    store.commit("resetHomeBread");
    if(to.meta && to.meta.name && to.path != "/") {
        store.commit("addBread", { text: to.meta.name, path: to.path });
    }
}


export default router
